package com.makemoney.miniprogram.common.config;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class SpringDocConfig {
    /**
     * token请求头名称
     */
    public static final String TOKEN_HEADER_NAME = "Authorization";

    @Bean
    public OpenAPI openApi(final SpringDocProperties docInfo) {
        OpenAPI api = new OpenAPI();
        if (ObjectUtil.isNotNull(docInfo.getSecurityEnabled()) && docInfo.getSecurityEnabled()) {
            Map<String, SecurityScheme> map = new HashMap<>();
            map.put(TOKEN_HEADER_NAME,new SecurityScheme().type(SecurityScheme.Type.APIKEY).in(SecurityScheme.In.HEADER).name(TOKEN_HEADER_NAME));
            api.components(new Components().securitySchemes(map));
            map.keySet().forEach(key -> api.addSecurityItem(new SecurityRequirement().addList(key)));
        }
        api.info(new Info().title(docInfo.getTitle())
                .description(docInfo.getDescription())
                .version(docInfo.getProjectVersion())
                .contact(new Contact()
                        .name(docInfo.getContact().getName())
                        .email(docInfo.getContact().getEmail())));
        return api;
    }
}
